﻿using UnityEngine;
using System.Collections;

public class Health : MonoBehaviour {

	//http://www.youtube.com/watch?v=CnKc9k6shQA


	public float hitPoints = 100f;
	float currentHitPoints;
	public float DeathVelocity;
	public Vector3 eulerAngleVelocity = new Vector3(0, 90, 0);
	bool dead = false;
	public GameObject Weapon;
	public Transform WeaponDrop;
	public Transform spawnDrop;
	bool shielded;
	float shieldTime;


	// Use this for initialization
	void Start () {
		currentHitPoints = hitPoints;
	}

	void Update(){
		if (shielded && Time.time - shieldTime > 5f) {
			shielded = false;
		}
	}

	public void setShield(){
		shielded = true;
		shieldTime = Time.time;
	}

	public void TakeDamage(float amt, Collision collision) {
		if (!dead && !shielded) {
			currentHitPoints -= amt;
			if (currentHitPoints <= 0) {
				Die (collision);
			}
		}
	}
	

	void Die(Collision collision){
		dead = true;
		if (transform.root.tag == "Player") {
			/*PlayerScript script = (PlayerScript)transform.root.GetComponent ("PlayerScript");
			currentHitPoints = hitPoints;
			script.respawn ();*/
		} else if (transform.root.tag == "Enemy") {
			GetComponent<EnemyMoveScript>().enabled = false;
			GetComponent<EnemyDetectionScript>().enabled = false;
			GetComponent<NavMeshAgent>().enabled = false;
			Vector3 direction = transform.position - collision.contacts[0].point;

			rigidbody.velocity = transform.up * DeathVelocity;
			Quaternion deltaRotation = Quaternion.Euler(eulerAngleVelocity * Time.deltaTime*2f);
			rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);
			renderer.material.color = Color.black;


			Destroy(Weapon.gameObject);
			Instantiate(WeaponDrop, spawnDrop.position, spawnDrop.rotation);
		    
			//GetComponent<BoxCollider>().enabled = false;

		} else {
			Destroy (gameObject);
		}
   }
	
}